package com.adminkk.factory;

import com.adminkk.annotation.Controller;
import com.adminkk.annotation.RequestMapping;
import com.adminkk.exception.MvcException;
import com.adminkk.handler.Handler;
import com.adminkk.handler.HandlerMapping;

import java.lang.reflect.Method;

public class MvcBeanPostProcessor implements BeanPostProcessor{


    //扫描Controller业务
    @Override
    public Object postProcessBeforeInitialization(Object object, String beanName) throws MvcException {

        Class<?> objectClass = object.getClass();
        if(objectClass.getAnnotation(Controller.class) != null){
            RequestMapping calssRequestMappingAnnotation = objectClass.getAnnotation(RequestMapping.class);
            StringBuilder urlSb = new StringBuilder();
            if(calssRequestMappingAnnotation != null){
                urlSb.append(calssRequestMappingAnnotation.value());
            }
            Method[] methods = objectClass.getMethods();
            if(methods != null && methods.length > 0 ){
                for (int i = 0; i < methods.length; i++) {
                    Method method = methods[i];
                    RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
                    if(methodAnnotation != null){
                        String methodValue = methodAnnotation.value();
                        String url = new StringBuilder().append(urlSb).append(methodValue).toString();
                        Handler handler = HandlerMapping.getHandlerMapping(url);
                        if(handler == null){
                            handler = new Handler();
                            handler.setMethod(method);
                            handler.setInstance(object);
                            HandlerMapping.addHandlerMapping(url,handler);
                        }else {
                            throw new MvcException("请求路径"+ url + "已经存在容器中");
                        }
                    }
                }

            }
        }

        return object;
    }

    @Override
    public Object postProcessAfterInitialization(Object object, String beanName) throws MvcException {
        return null;
    }
}
